package org.hiberlyzer.ui;

import java.awt.Component;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;

import org.hiberlyzer.DataColumn;

public class DataSetTable extends JTable
{
	
	public DataSetTable(final QueryWindow queryWindow)
	{
		super(new EmptyTableModel());
		setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // without this, columns will be smashed to fit window
		addMouseListener(new MouseAdapter()
		{
		    public void mouseClicked(MouseEvent e)
		    {
		        if (e.getClickCount() == 2)
		        {
		            Point p = e.getPoint();
		            int rowViewIndex = rowAtPoint(p);
		            int columnViewIndex = columnAtPoint(p);
		            Object value = getValueAt(rowViewIndex, columnViewIndex);
		            // translate to model index in case user has re-ordered columns
		            int columnModelIndex = getColumnModel()
		            	.getColumn(columnViewIndex).getModelIndex();
		            DataColumn dataColumn = getModel().getDataColumn(columnModelIndex);
		            if(value != null && dataColumn.hasMetadata())
		            {
		            	queryWindow.displayDetailDialog(value, dataColumn);
		            }
		        }
		    }
		});
	}
	
	@Override
	public DataSetTableModel getModel()
	{
		return (DataSetTableModel) super.getModel();
	}

	@Override
	// defer rendering of cell to the data column itself
	public TableCellRenderer getCellRenderer(int row, int column)
	{
		Object value = getValueAt(row, column);
		int columnModelIndex = getColumnModel()
    		.getColumn(column).getModelIndex();
		final String textValue = (getModel().getDataColumn(columnModelIndex).formatValue(value));
		return new DefaultTableCellRenderer(){

			@Override
			public Component getTableCellRendererComponent(JTable table,
					Object value, boolean isSelected, boolean hasFocus,
					int row, int column)
			{
				return super.getTableCellRendererComponent(table, textValue, isSelected, hasFocus,
						row, column);
			}};
	}
}
